package com.leyou.user.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.leyou.common.exception.MyException;
import com.leyou.common.utils.RegexUtils;
import com.leyou.user.dto.UserDTO;
import com.leyou.user.entity.User;
import com.leyou.user.mapper.UserMapper;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import static com.leyou.common.constants.MQConstants.ExchangeConstants.SMS_EXCHANGE_NAME;
import static com.leyou.common.constants.MQConstants.RoutingKeyConstants.VERIFY_CODE_KEY;

@Service
public class UserService extends ServiceImpl<UserMapper, User> implements com.leyou.user.service.UserService {
    @Autowired
    private BCryptPasswordEncoder passwordEncoder;
    @Override
    public UserDTO queryUserByPhoneAndPassword(String username, String password) {
        List<User> users = query().eq("username", username).list();
        if (users.size() == 0) {
            throw new MyException(400,"没有该用户");
        }
        User user = users.get(0);
        if (!passwordEncoder.matches(password,user.getPassword())) {
            throw new MyException(400, "密码输入错误");
        }

        return new UserDTO(user);
    }
    @Autowired
    private StringRedisTemplate redisTemplate;
    @Autowired
    private AmqpTemplate amqpTemplate;

    private final String KEY_PREFIX = "ly.user.verify:";

    @Override
    @Transactional
    public void registerUser(User user, String code) {
       String key=KEY_PREFIX+user.getPhone();
        if (StringUtils.isEmpty(code) || !code.equals(redisTemplate.opsForValue().get(key))) {
            throw new MyException(400, "验证码错误");
        }
        //对密码进行加密，生成随机盐值，优点，盐值不外露
        String encodePassword = passwordEncoder.encode(user.getPassword());
        user.setPassword(encodePassword);
        this.save(user);
    }

    @Override
    public Boolean exists(String data, Integer type) {
        String colName = null;
        switch (type) {
            case 1:
                colName = "username";
                if (StringUtils.isEmpty(data)) {
                    throw new MyException(400, "查询参数有误");
                }
                break;
            case 2:
                colName = "phone";
                if (!RegexUtils.isPhone(data)) {
                    throw new MyException(400, "查询参数有误");
                }
                break;
            default:
                throw new MyException(400, "查询参数有误");
        }
        return this.query().eq(colName, data).count() == 1;
    }

    @Override
    public void sendcode(String phone) {
        if (!RegexUtils.isPhone(phone)) {
            throw new MyException(400, "请求参数有误");
        }
        Map<String, String> msg=new HashMap<>();
        msg.put("phone", phone);
        String code = RandomStringUtils.randomNumeric(6);
        msg.put("code", code);
        amqpTemplate.convertAndSend(SMS_EXCHANGE_NAME, VERIFY_CODE_KEY, msg);
        String key = KEY_PREFIX + phone;
        //验证码redis存储
        this.redisTemplate.opsForValue().set(key, code, 5, TimeUnit.MINUTES);

    }
}
